package com.itany.shop.controller;

import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年09月12日16:29
 */

@WebServlet("*.user")
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String path=request.getServletPath();
        switch (path){
            case "/register.user":
                register(request,response);
                break;
            case "/login.user":
                login(request,response);
                break;
        }
    }
    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String phone=request.getParameter("phone");
        String address=request.getParameter("address");
        UserService userService= (UserService) ObjectFactory.getObject("userService");
        try {
            userService.register(username,password,phone,address);
            response.sendRedirect(request.getContextPath()+"/jsp/login.jsp");
        } catch (RequestParameterErrorException e) {
            e.printStackTrace();
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (UserExistException e) {
            e.printStackTrace();
            request.setAttribute("registerMsg",e.getMessage());
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("registerMsg","服务器内部异常");
            request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);
        }

    }
    public void  login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取用户名，获取密码，获取验证码

        response.sendRedirect(request.getContextPath()+"/findAll.product");
    }
}
